package com.shawn.baseappbygroovydsl.ui.views

import android.os.Bundle
import android.view.View
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.shawn.baseappbygroovydsl.R
import com.shawn.baseappbygroovydsl.databinding.FragmentScopeBinding
import com.shawn.baseappbygroovydsl.ui.base.FragmentBase
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.supervisorScope
import kotlinx.coroutines.withTimeout
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext

class ScopeFragment  : FragmentBase<FragmentScopeBinding>(R.layout.fragment_scope) {
    private val scopeViewModel by lazy {
        val vm: ScopeViewModel = ViewModelProvider(requireActivity())[ScopeViewModel::class.java]
        vm
    }
    companion object {
        fun newInstance(): ScopeFragment {
            val args = Bundle()
            val fragment = ScopeFragment()
            fragment.arguments = args
            return fragment
        }
    }

    override fun onKeyCodeBack(): Boolean {
        return false
    }

    override fun statusBar() {

    }

    override fun lazyLoad() {

    }

    override fun initClick() {

    }

    override fun getData() {
        dispatchersSample()
//        scope2()
        scope3()
    }

    override fun getBind(view: View): FragmentScopeBinding {
        return FragmentScopeBinding.bind(view)
    }

    /**
     * 自定义协程
     * */
    object MyGlobalScope : CoroutineScope {
        override val coroutineContext: CoroutineContext
            get() = EmptyCoroutineContext
    }

    fun MyGlobalScope() {
        MyGlobalScope.launch {

        }
    }

    private suspend fun doSomething() {
        delay(1000)
        println("println doSomething")
    }

    fun normalLaunchAndAsync() {
        // 方式1: launch - 用于执行不需要返回结果的异步任务
        lifecycleScope.launch {
            // 异步代码
            doSomething()
        }

        // 方式2: async - 用于需要返回结果的异步任务
        val deferred = lifecycleScope.async {

        }
        lifecycleScope.launch {
            val result = deferred.await()
        }
    }


    private fun dispatchersSample() {
        viewLifecycleOwner.lifecycleScope.launch {
            launch(Dispatchers.Main) {
                // UI更新
            }
            launch(Dispatchers.IO) {
                // 网络请求、文件操作、数据库访问
            }
            launch(Dispatchers.Default) {
                // CPU 密集型计算、排序、复杂逻辑
            }
            launch(Dispatchers.Unconfined) {
                // 不限制特定线程（不推荐常规使用）
            }
        }
    }

    private fun apiRequest() {
        viewLifecycleOwner.lifecycleScope.launch {
//            try {
//                val user = apiService.getUser(userId).await()
//                _userLiveData.value = user
//            } catch (e: Exception) {
//                _errorLiveData.value = e.message
//            }
        }
        viewLifecycleOwner.lifecycleScope.launch {
//            val userDeferred = async { apiService.getUser(userId) }
//            val postsDeferred = async { apiService.getUserPosts(userId) }
//
//            val user = userDeferred.await()
//            val posts = postsDeferred.await()
//
//            // 合并结果
//            _userWithPosts.value = UserWithPosts(user, posts)
        }
        viewLifecycleOwner.lifecycleScope.launch {
//            val token = apiService.login(username, password).await()
//            val user = apiService.getUserProfile(token).await()
//            val settings = apiService.getUserSettings(user.id).await()
//
//            _completeUserData.value = UserData(user, settings)
        }
        viewLifecycleOwner.lifecycleScope.launch {
//            try {
//                val result = withTimeout(5000) { // 5秒超时
//                    apiService.getLargeData().await()
//                }
//                _data.value = result
//            } catch (e: TimeoutCancellationException) {
//                _error.value = "请求超时"
//            }
        }
    }

    private fun cancelJob() {
        viewLifecycleOwner.lifecycleScope.launch {
            val job = launch {
                delay(2000)
                println("println job")
            }
            delay(1000)
            job.cancel()
        }
    }

    private fun supervisorScopeSample() {
        viewLifecycleOwner.lifecycleScope.launch {
            supervisorScope {
                val job1 = launch {
                    delay(2000)
                    // 如果抛出异常 ， job1 停止执行 ， job2 继续执行
                    throw NullPointerException()
                }

                val job2 = launch {
                    delay(2000)
                    println("println supervisorScope job 2")
                }
                // 如果执行 cancel ,job 1 ， job 2 均取消
            }
        }
    }

    private fun scope2() {
        viewLifecycleOwner.lifecycleScope.launch {

            coroutineScope {
                try {
                    val job1 = launch {
                        delay(2000)
                        // 如果抛出异常 ， job1 停止执行 ， job2 也会被取消，停止执行
                        throw NullPointerException()
                    }

                    val job2 = launch {
                        delay(2000)
                        println("println coroutineScope job 2")
                    }
                    // 如果执行 cancel ,job 1 ， job 2 均取消
                    // cancel()
                } catch (e: Throwable) {
                    // ignore
                }
            }

            try {
                supervisorScope {
                    val job1 = launch {
                        delay(2000)
                        // 如果抛出异常 ， job1 停止执行 ， job2 继续执行
                        throw NullPointerException()
                    }

                    val job2 = launch {
                        delay(2000)
                        println("println supervisorScope job 2")
                    }
                    // 如果执行 cancel ,job 1 ， job 2 均取消
                    // cancel()
                }
            } catch (e: Throwable) {
                // ignore
            }

            try {
                coroutineScope {
                    val job1 = launch {
                        delay(2000)
                        // 如果抛出异常 ， job1 停止执行 ， job2 也会被取消，停止执行
                        throw NullPointerException()
                    }

                    val job2 = launch {
                        delay(2000)
                        println("println coroutineScope job 2")
                    }
                    // 如果执行 cancel ,job 1 ， job 2 均取消
                    // cancel()
                }
            } catch (e: Throwable) {
                // ignore
            }

            try {
                supervisorScope {
                    val job1 = launch {
                        delay(2000)
                        // 如果抛出异常 ， job1 停止执行 ， job2 继续执行
                        throw NullPointerException()
                    }

                    val job2 = launch {
                        delay(2000)
                        println("println supervisorScope job 2")
                    }
                    // 如果执行 cancel ,job 1 ， job 2 均取消
                    // cancel()
                }
            } catch (e: Throwable) {
                // ignore
            }
        }
    }

    private fun scope3() {
        lifecycleScope.launch() {
            val job1 = launch {
                delay(1000)
                println("println job1")
            }

            launch(SupervisorJob(coroutineContext[Job])) {
                val supervisorJob1 = launch {
                    delay(1000)
                    // 如果抛出异常 ， job1 停止执行 ， job2 继续执行
                    throw NullPointerException()
                }

                val supervisorJob2 = launch {
                    delay(2000)
                    println("println SupervisorJob job2")
                }
            }
        }
    }

    private fun scope4() {
        scopeViewModel.text.observe(viewLifecycleOwner) {

        }
    }
}